import { defineStore } from 'pinia'
import { ref } from 'vue'

// 定义 Store
export const useUserStore = defineStore(
  'user',
  () => {
    // 用户token
    const token = ref('')

    // 保存token信息
    const setToken = (value) => {
      token.value = value
    }

    // 清理token信息，退出时使用
    const clearToken = () => {
      token.value = null
    }

    // 用户信息
    const userInfo = ref({
      company_id: '',
      env_company: '',
      uid: '',
      username: '',
      name: '',
      //数据中的组织(company_id)必须在下面登录用户所属组织的列表内才能查看，即组织隔离
      companies: [],
      user_context: {},
    })
    const setUserInfo = (value) => {
      userInfo.value = value
    }
    const setUserInfoItem = (key, value) => {
      userInfo.value[key] = value
    }
    const clearUserInfo = () => {
      userInfo.value = {}
    }

    const actionType = ref('online') //offline
    const setActionType = (value) => {
      actionType.value = value
    }
    const clear = () => {
      userInfo.value = {}
      token.value = null
      actionType.value = 'offline'
    }

    // 记得 return
    return {
      token,
      setToken,
      clearToken,
      userInfo,
      setUserInfo,
      setUserInfoItem,
      clearUserInfo,
      actionType,
      setActionType,
      clear,
    }
  },
  {
    // 网页端配置
    // persist: true,
    // 小程序端配置
    persist: {
      storage: {
        getItem(key) {
          return uni.getStorageSync(key)
        },
        setItem(key, value) {
          return uni.setStorageSync(key, value)
        },
      },
    },
  },
)
